package com.hoshiicloud.as2c.minipro.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

/**
 * @author yangcheng
 * @version 1.0
 * @title: WXCore
 * @description: 微信对外工具类
 * @date 2019/6/17 14:19
 * @mail maiboyc@163.com
 */
public class WXCore {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";

    /**
     * 解密数据
     *
     * @return String
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv) {
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSON.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if (!appId.equals(decryptAppid)) {
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws Exception {

        String appId = "wx4f4bc4dec97d474b";
        String encryptedData = "7dsE5YeqkHgqMQIoxuGud6mjrB+7VvQJqat0DeH7+qmuQK3ssWuMvAIOUpj4bNSk6nuk7qJzO7EgPw2LW/CDdZycY19k0qMd9hSgvxJutiCxWNelnr7ByoA0ZVtzjA2/A6U0gK33YaR1u0QMPQtbiHMb+2zszsCon3YkL+0AtmTvUNGBzq0GzxAE8g9+1dgrOZsTFVKEF4y26CU2Xv8Aqw==";
        String sessionKey = "tiihtNczf5v6AKRyjwEUhQ==";
        String iv = "5un4ZBbAD1fvKSoynzreOw==";
        System.out.println(decrypt(appId, encryptedData, sessionKey, iv));
    }

}
